

layui.use(['layer','element','form','upload'], function() {
    var	$ = layui.jquery,
        element = layui.element,
        form = layui.form,
        upload = layui.upload;

    form.render();


    // 搜索
    $(".btn-search-form").click(function () {
        var miniKeywords = $("input[name=miniKeywords]").val();
        $.post('index.php?route=Hero/index&iActId=1001',{miniKeywords:miniKeywords},function (res) {
            if(res.status =="error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                if (res.data.length>0) {
                    var html = '';
                    $.each(res.data,function(i,val){  //遍历二维数组
                        html += ' <button type="button" data-value="'+val.id+'" class="action-mini layui-btn">'+val.name+'</button>'
                    });
                    $("#mini-btn-search").html(html);
                    $("#mini-btn-search").find(".action-mini").first().trigger('click');
                }
                return;
            }
        });
        return;
    });

    // 搜索英雄
    $(".btn-search-form-hero").click(function () {
        $("#hero-list").html('');
        var keywords = $("input[name=keywords]").val();
        var miniId = $("input[name=miniId]").val();
        var that = this;
        $.post('/index.php?route=Hero/getHeroByMiniId&iActId=1001', {miniId: miniId, keywords: keywords}, function (res) {
            if (res.status == "error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                if (!res.data.length) {
                    $(".hero-form-edit").hide();
                } else {
                    eachHeroData(res.data)
                }
            }
        })
    });

    //点击上方英雄所属
    $("#mini-btn-search").on('click','.action-mini',function () {
        $("#hero-list").html('');
        var miniId = $(this).data('value');
        $("#heroMiniId").val(miniId);
        var that = this;
        $.post('/index.php?route=Hero/getHeroByMiniId&iActId=1001',{miniId:miniId},function (res) {
            if(res.status =="error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                if (!res.data.length) {
                  $(".hero-form-edit").hide();
                } else {
                    eachHeroData(res.data)
                }
            }

        })
    })

    function eachHeroData(data) {
        var html = '';
        if (data && data != '' && data.length>0) {
            $("#hero-list").find(".hero-item").first().trigger('click');
            $.each(data, function (i, item) {  //遍历二维数组
                html += '<li class="hero-item" data-heroid="' + item.heroId + '"><img src="' + item.imagePath + '" alt=""><p>' + item.name + '</p></li>';
            });
            $("#hero-list").html(html);
            $("#hero-list").find(".hero-item").first().trigger('click');
        }
    }

    $(".action-mini").first().trigger('click');
    $("#heroMiniId").val($(".action-mini").first().data('value'));

    //点击英雄头像
    $("#hero-list").on('click','.hero-item',function () {
        var that = this;

        var data = {heroId:$(this).data('heroid')};
        $.post('/index.php?route=Hero/getHeroInfo&iActId=1001',data,function (res) {
            if(res.status =="error") {
                layer.msg(res.msg);//失败的表情
                return;
            } else {
                $(".hero-form-edit").show();
                $(that).siblings().removeClass('active');
                $(that).addClass('active');

                /*$("#hero-form").find('input').attr('disabled',true);
                $("#hero-form").find('select').attr('disabled',true);
                $("#hero-form").find('.action-to-update').show();
                $("#hero-form").find('.action-to-submit').hide();*/

                var data = res.data;

                $("#hero-form").find("[name='typeId']").val(data.typeId);
                $("#hero-form").find("[name='miniId']").val(data.miniId);


                $("#hero-form").find("[name='name']").val(data.name);
                $("#hero-form").find("[name='heroId']").val(data.heroId);
                $("#hero-form").find("[name='heroIdShow']").text(data.heroId);

                $("#hero-form").find("[name='star']").val(data.star);
                $("#hero-form").find("[name='imagePath']").val(data.imagePath);
                $("#image-path").attr('src',data.imagePath);
                $("#hero-form").find("[name='shape']").val(data.shape);
                $("#hero-form").find("[name='quality']").val(data.quality);


                form.render();
            }

        })
    })
    //点击删除
    $("#hero-form").on('click','.action-to-delete',function () {
        layer.confirm('是否要删除该数据？', {icon: 3, title:'提示'}, function(index){
            var dataType = 3;
            var id = $('#hero-form').find("input[name=heroId]").val()
            layer.close(index);
            var url = "/index.php?route=Main/deleteData&iActId=1001";
            $.ajax({
                url: url, type: "post", dataType: "json",
                data: { dataType:dataType,id:id},
                beforeSend:function () {
                    this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
                },
                success:function(data){
                    if(data.status =="error"){
                        layer.msg(data.msg);//失败的表情
                        return;
                    }else if(data.status == "success"){
                        layer.msg(data.msg, {
                            icon: 1,//成功的表情
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            parent.$(".refresh").click();
                        });
                    }
                },
                complete: function () {
                    layer.close(this.layerIndex);
                },
            });
        });
    });

    //点击编辑
    /*$("#hero-form").on('click','.action-to-update',function () {
        $("#hero-form").find('input').removeAttr('disabled');
        $("#hero-form").find('select').removeAttr('disabled');

        $("#hero-form").find('.action-to-update').hide();
        $("#hero-form").find('.action-to-submit').show();

        form.render();

    });*/
    //点击保存

    $("#hero-form").on('click','.action-to-submit',function () {
        if (checkFormData($("#hero-form"))) {

            var data = $('#hero-form').serialize();

            $.post('/index.php?route=Hero/update&iActId=1001', data, function (res) {
                if (res.status == "error") {
                    layer.msg(res.msg);//失败的表情
                    return;
                } else {
                   /* $("#hero-form").find('input').attr('disabled', true);
                    $("#hero-form").find('select').attr('disabled', true);
                    $("#hero-form").find('.action-to-update').show();
                    $("#hero-form").find('.action-to-submit').hide();*/
                    layer.msg('编辑成功');
                }
            });
        }
    });

    //更换图标

     upload.render({
        elem: '#image' //绑定元素
        ,url:'/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
         , accept: 'images'
         ,data:{
            id:1,
             type:'hero'
         }
        ,done: function(res){
             $("#hero-form").find("[name='imagePath']").val(res.imagePath);
             $("#image-path").attr('src',res.imagePath);
             $("#hero-list").find('.active').find('img').attr('src',res.imagePath);
            //上传完毕回调
        }
        ,error: function(){
            //请求异常回调
        }
    });

    // 添加英雄所属
    $(".hero-mini-add").on('click', function(){
        layer.open({
            title: '添加英雄所属',
            type: 1,
            area:['317px','228px'],
            content: $(".hero-mini-form"),
            skin: 'layui-layer-rim', //加上边框
            end:function (res) {
                $(".hero-mini-form").hide();
            }
        });
    });

    form.on('submit(hero-mini-filter)', function(data){
        $.ajax({
            url: "/index.php?route=Hero/addHeroMini&iActId=1001",
            type: 'POST',
            dataType: 'JSON',
            data: $(".hero-mini-form").serializeArray(),
            success: function (res) {
                if (res.status == 'success') {
                    window.location.reload();//刷新父页面
                } else {
                    layer.msg(res.msg);
                    return false;
                }
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    // 添加英雄类型
    $(".hero-type-add").on('click', function(){
        layer.open({
            title: '添加英雄类型',
            type: 1,
            area:['317px','228px'],
            content: $(".hero-type-form"),
            skin: 'layui-layer-rim', //加上边框
            end:function (res) {
                $(".hero-type-form").hide();
            }
        });
    });

    form.on('submit(hero-type-filter)', function(data){
        $.ajax({
            url: "/index.php?route=Hero/addHeroType&iActId=1001",
            type: 'POST',
            dataType: 'JSON',
            data: $(".hero-type-form").serializeArray(),
            success: function (res) {
                if (res.status == 'success') {
                    window.location.reload();//刷新父页面
                } else {
                    layer.msg(res.msg);
                    return false;
                }
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    /*添加英雄*/
    $(".hero-add").on('click', function(){
        layer.open({
            title: '添加英雄',
            type: 1,
            area:['485px','600px'],
            content: $(".hero-add-form"),
            skin: 'layui-layer-rim', //加上边框
            end:function (res) {
                $(".hero-add-form").hide();
            }
        });
    });

    form.on('submit(hero-filter)', function(data){
        if (checkFormData($(".hero-add-form"))) {
            $.ajax({
                url: "/index.php?route=Hero/addHero&iActId=1001",
                type: 'POST',
                dataType: 'JSON',
                data: $(".hero-add-form").serializeArray(),
                success: function (res) {
                    if (res.status == 'success') {
                        window.location.reload();//刷新父页面
                    } else {
                        layer.msg(res.msg);
                        return false;
                    }
                }
            });
        }
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    upload.render({
        elem: '#heroImg' //绑定元素
        ,url:'/index.php?route=LolApi/uploadImg&iActId=1001' //上传接口
        , accept: 'images'
        ,data:{
            id:1,
            type:'hero'
        }
        ,done: function(res){
            $(".hero-add-form").find("[name='imagePath']").val(res.imagePath);
            $("#add-image-path").attr('src',res.imagePath);
        }
        ,error: function(){
            //请求异常回调
        }
    });
    
    function checkFormData(box) {
        var heroId = box.find("input[name=heroId]").val();
        if (isNaN(heroId) || heroId == '') {
            layer.msg('英雄ID必须为数字类型');
            return false;
        }
        var name = box.find("input[name=name]").val();
        if (name == '') {
            layer.msg('英雄名称不能为空');
            return false;
        }
        var imagePath = box.find("input[name=imagePath]").val();
        if (imagePath == '') {
            layer.msg('请上传图片');
            return false;
        }
        var typeId = box.find("select[name=typeId]").val();
        if (isNaN(typeId) || typeId == '') {
            layer.msg('请选择英雄类型');
            return false;
        }
        var miniId = box.find("select[name=miniId]").val();
        if (isNaN(miniId) || miniId == '') {
            layer.msg('请选择英雄所属');
            return false;
        }
        var star = box.find("input[name=star]").val();
        if (isNaN(star) || star == '') {
            layer.msg('英雄星级必须为数字类型');
            return false;
        }

        var shape = box.find("select[name=shape]").val();
        if (shape == '') {
            layer.msg('请选择英雄形态');
            return false;
        }

        var quality = box.find("select[name=quality]").val();
        if (quality == '') {
            layer.msg('请选择英雄品质');
            return false;
        }
        return true;
    }


})





